﻿#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

class CFileLink
{
    fstream file1, file2, file3; // 声明3个流对象
    char fn1[20], fn2[20], fn3[20];

public:
    CFileLink();               // 打开连接的两个文件，创建连接后的结果文件
    ~CFileLink();              // 关闭文件
    void writeFixedData();     // 向两个源文件写入固定数据
    void displaySourceFiles(); // 显示源文件内容
    void linkfile();           // 读取两个源文件,写入结果文件
    void prtfile();            // 输出结果文件
};

CFileLink::CFileLink()
{
    strcpy(fn1, "file1.txt");  // 源文件1
    strcpy(fn2, "file2.txt");  // 源文件2
    strcpy(fn3, "result.txt"); // 结果文件

    // 以读写模式打开源文件，如果不存在则创建
    file1.open(fn1, ios::in | ios::out | ios::trunc);
    file2.open(fn2, ios::in | ios::out | ios::trunc);
    file3.open(fn3, ios::in | ios::out | ios::trunc);

    if (!file1 || !file2 || !file3) {
        cout << "Error opening files!" << endl;
        exit(1);
    }
}

CFileLink::~CFileLink()
{
    file1.close();
    file2.close();
    file3.close();
}

// 向源文件写入固定数据
void CFileLink::writeFixedData()
{
    // 重置文件指针并清除状态标志
    file1.clear(); file1.seekp(0);
    file2.clear(); file2.seekp(0);

    file1 << "This is the content of File 1.\n";
    file1 << "It contains some sample text.\n";
    file1 << "File linking demonstration.\n";

    file2 << "CONTENT OF FILE 2:\n";
    file2 << "More sample text here.\n";
    file2 << "End of file 2 content.\n";
}

// 显示源文件内容
void CFileLink::displaySourceFiles()
{
    string line;

    cout << "\nContent of " << fn1 << ":\n";
    file1.clear(); // 清除状态标志
    file1.seekg(0); // 确保从文件头开始读取
    while (getline(file1, line)) {
        cout << line << endl;
    }

    cout << "\nContent of " << fn2 << ":\n";
    file2.clear();
    file2.seekg(0);
    while (getline(file2, line)) {
        cout << line << endl;
    }
}

// 读取两个源文件,写入结果文件
void CFileLink::linkfile()
{
    string line;

    // 重置文件指针并清除状态标志
    file1.clear(); file1.seekg(0);
    file2.clear(); file2.seekg(0);
    file3.clear(); file3.seekp(0);

    // 写入第一个文件内容
    while (getline(file1, line)) {
        file3 << line << endl;
    }

    // 写入第二个文件内容
    while (getline(file2, line)) {
        file3 << line << endl;
    }
}

void CFileLink::prtfile()
{
    string line;

    file3.clear(); // 清除状态标志
    file3.seekg(0); // 确保从文件头开始读取

    cout << "\nThe content of the result file is:" << endl;
    while (getline(file3, line)) {
        cout << line << endl;
    }
}

int main()
{
    CFileLink flink;

    // 向源文件写入固定数据
    flink.writeFixedData();

    // 显示源文件内容
    cout << "Source files content:" << endl;
    flink.displaySourceFiles();

    // 连接文件
    flink.linkfile();

    // 输出结果文件内容
    flink.prtfile();

    return 0;
}